package com.vil.controller;

import com.vil.common.Constants;
import com.vil.common.ServerResponse;
import com.vil.entity.Admin;
import com.vil.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("login")
public class LoginController extends BaseController{


    @Autowired
    private AdminService adminService;

    //去登录页面
    @RequestMapping("login.html")
    public String toLogin(){
        return "admin/login";
    }

    //登录验证
    @PostMapping("doLogin.html")
    @ResponseBody
    public ServerResponse toIndex(@RequestParam("login_code")String login_code,
                                  @RequestParam("password") String password, HttpSession session){
        ServerResponse loginCheck = adminService.loginCheck(login_code, password);
        if (loginCheck!=null){
            Admin data = (Admin)loginCheck.getData();
            if (data.getStatus()==0){
                return  ServerResponse.buildErrorMsg("您的账号未激活，不能登录");
            }
            session.setAttribute(Constants.USER_SESSION,data);
            return ServerResponse.buildSuccessMsg("登陆成功");
        }
        return  ServerResponse.buildErrorMsg("账号或密码错误");
    }


    //退出登录
    @RequestMapping("logout")
    public String logout(HttpSession session){
        Admin currentAdmin = (Admin) session.getAttribute(Constants.USER_SESSION);
        if (currentAdmin==null){
            return "admin/login";
        }
        session.invalidate();
        return "admin/login";
    }

}
